#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flight策略部署脚本
一键部署多账号Flight策略系统
"""

import os
import json
import time
from datetime import datetime
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

def check_environment():
    """检查环境配置"""
    print("🔍 检查环境配置...")
    
    required_vars = {
        'OKX_DEMO_API_KEY': os.getenv('OKX_DEMO_API_KEY'),
        'OKX_DEMO_SECRET': os.getenv('OKX_DEMO_SECRET'),
        'OKX_DEMO_PASSWORD': os.getenv('OKX_DEMO_PASSWORD'),
        'DEEPSEEK_API_KEY': os.getenv('DEEPSEEK_API_KEY'),
        'TELEGRAM_BOT_TOKEN': os.getenv('TELEGRAM_BOT_TOKEN'),
        'TELEGRAM_CHAT_ID': os.getenv('TELEGRAM_CHAT_ID')
    }
    
    missing = []
    for var, value in required_vars.items():
        if not value:
            missing.append(var)
        else:
            print(f"✅ {var}: {value[:10]}...")
    
    if missing:
        print(f"❌ 缺少环境变量: {missing}")
        return False
    else:
        print("✅ 所有环境变量都已设置")
        return True

def check_flight_strategy():
    """检查Flight策略模块"""
    print("\n🔍 检查Flight策略模块...")
    
    try:
        import flight_strategy
        print("✅ Flight策略模块导入成功")
        
        # 检查关键函数
        required_functions = [
            'analyze_with_flight',
            'get_flight_ohlcv_data', 
            'init_flight_exchange',
            'FLIGHT_CONFIG'
        ]
        
        for func_name in required_functions:
            if hasattr(flight_strategy, func_name):
                print(f"✅ {func_name} 存在")
            else:
                print(f"❌ {func_name} 不存在")
                return False
        
        return True
        
    except ImportError as e:
        print(f"❌ Flight策略模块导入失败: {e}")
        return False

def check_multi_account_manager():
    """检查多账号管理器"""
    print("\n🔍 检查多账号管理器...")
    
    try:
        import multi_account_manager
        print("✅ 多账号管理器导入成功")
        return True
        
    except ImportError as e:
        print(f"❌ 多账号管理器导入失败: {e}")
        return False

def load_accounts_config():
    """加载账户配置"""
    print("\n🔍 加载账户配置...")
    
    try:
        with open('accounts_config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        print("✅ accounts_config.json 加载成功")
        
        # 统计Flight策略账户
        flight_accounts = []
        total_accounts = 0
        enabled_accounts = 0
        
        for account_id, account_config in config['accounts'].items():
            total_accounts += 1
            if account_config.get('enabled', False):
                enabled_accounts += 1
                if account_config.get('strategy') == 'flight':
                    flight_accounts.append((account_id, account_config))
        
        print(f"📊 账户统计:")
        print(f"   总账户数: {total_accounts}")
        print(f"   启用账户数: {enabled_accounts}")
        print(f"   Flight策略账户数: {len(flight_accounts)}")
        
        if flight_accounts:
            print(f"\n📋 Flight策略账户详情:")
            for account_id, account_config in flight_accounts:
                print(f"   🎯 {account_id}: {account_config['name']}")
                print(f"      杠杆: {account_config['config']['leverage']}x")
                print(f"      仓位比例: {account_config['config']['position_size_ratio']*100:.1f}%")
                print(f"      交易对: {len(account_config['config']['symbols'])}个")
        
        return config, flight_accounts
        
    except Exception as e:
        print(f"❌ 加载配置失败: {e}")
        return None, []

def test_flight_strategy_quick():
    """快速测试Flight策略"""
    print("\n🧪 快速测试Flight策略...")
    
    try:
        import flight_strategy
        
        # 初始化交易所
        exchange = flight_strategy.init_flight_exchange(use_demo=True)
        if not exchange:
            print("❌ Flight交易所初始化失败")
            return False
        
        print("✅ Flight交易所初始化成功")
        
        # 测试数据获取
        symbol = 'BTC/USDT:USDT'
        price_data = flight_strategy.get_flight_ohlcv_data(symbol)
        
        if not price_data:
            print(f"❌ {symbol} 数据获取失败")
            return False
        
        print(f"✅ {symbol} 数据获取成功: ${price_data['price']:,.2f}")
        
        # 测试策略分析
        signal_data = flight_strategy.analyze_with_flight(price_data, symbol)
        
        print(f"✅ Flight策略分析完成:")
        print(f"   信号: {signal_data['signal']}")
        print(f"   策略: {signal_data['strategy_used']}")
        print(f"   信心: {signal_data['confidence']}")
        
        return True
        
    except Exception as e:
        print(f"❌ Flight策略测试失败: {e}")
        return False

def deploy_flight_strategy():
    """部署Flight策略"""
    print("\n🚀 部署Flight策略系统")
    print("=" * 60)
    
    # 检查环境
    if not check_environment():
        return False
    
    # 检查Flight策略模块
    if not check_flight_strategy():
        return False
    
    # 检查多账号管理器
    if not check_multi_account_manager():
        return False
    
    # 加载配置
    config, flight_accounts = load_accounts_config()
    if not config:
        return False
    
    # 快速测试
    if not test_flight_strategy_quick():
        return False
    
    print(f"\n🎉 Flight策略部署检查完成！")
    print("=" * 60)
    
    if flight_accounts:
        print(f"✅ 发现 {len(flight_accounts)} 个Flight策略账户")
        print(f"\n🚀 启动命令:")
        print(f"   python multi_account_manager.py")
        print(f"\n📊 监控命令:")
        print(f"   tail -f logs/demo_flight_trading.log")
        print(f"\n📱 Telegram通知已启用")
        print(f"\n⚙️ 配置文件:")
        print(f"   accounts_config.json")
        
        return True
    else:
        print("❌ 未找到启用的Flight策略账户")
        print("请检查 accounts_config.json 中的配置")
        return False

def show_flight_accounts_status():
    """显示Flight策略账户状态"""
    print("\n📊 Flight策略账户状态")
    print("=" * 60)
    
    try:
        with open('accounts_config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        flight_accounts = []
        for account_id, account_config in config['accounts'].items():
            if account_config.get('strategy') == 'flight':
                status = "🟢 启用" if account_config.get('enabled', False) else "🔴 禁用"
                flight_accounts.append((account_id, account_config, status))
        
        if flight_accounts:
            print(f"找到 {len(flight_accounts)} 个Flight策略账户:\n")
            
            for account_id, account_config, status in flight_accounts:
                print(f"{status} {account_id}")
                print(f"   名称: {account_config['name']}")
                print(f"   描述: {account_config['description']}")
                print(f"   沙盒: {'是' if account_config.get('sandbox', True) else '否'}")
                print(f"   杠杆: {account_config['config']['leverage']}x")
                print(f"   仓位比例: {account_config['config']['position_size_ratio']*100:.1f}%")
                print(f"   每日限额: {account_config['config']['daily_trade_limit']}次")
                print(f"   止损比例: {account_config['config']['stop_loss_ratio']*100:.1f}%")
                print(f"   止盈比例: {account_config['config']['take_profit_ratio']*100:.1f}%")
                print(f"   交易对: {len(account_config['config']['symbols'])}个")
                
                symbols = [s['symbol'] for s in account_config['config']['symbols']]
                print(f"   交易对列表: {', '.join(symbols)}")
                print()
        else:
            print("❌ 未找到Flight策略账户")
            
    except Exception as e:
        print(f"❌ 读取配置失败: {e}")

def main():
    """主函数"""
    print("🎬 Flight策略部署工具")
    print(f"部署时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 80)
    
    import sys
    
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command == "status":
            show_flight_accounts_status()
        elif command == "deploy":
            if deploy_flight_strategy():
                print(f"\n🎯 部署成功！现在可以运行:")
                print(f"   python multi_account_manager.py")
            else:
                print(f"\n❌ 部署失败，请检查配置")
        elif command == "test":
            test_flight_strategy_quick()
        else:
            print(f"❌ 未知命令: {command}")
            print(f"可用命令: deploy, status, test")
    else:
        print("📖 使用方法:")
        print("   python deploy_flight_strategy.py deploy  # 部署检查")
        print("   python deploy_flight_strategy.py status  # 查看状态")
        print("   python deploy_flight_strategy.py test    # 快速测试")

if __name__ == "__main__":
    main()
